#include "TcpClient.h"

#include <QByteArray>
#include <QDataStream>
#include <QString>
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QLabel>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QCheckBox>
#include <QRegExpValidator>

TcpClient::TcpClient()
{
    customUI();
    // TCP
    connect(&tcpSocket, SIGNAL(disconnected()),
            this, SLOT(connectionClosedByServer()));
    connect(&tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(error(QAbstractSocket::SocketError)));
    connect(&tcpSocket, SIGNAL(connected()),
            this, SLOT(successed()));
    // ui
    connect(connectbtn,SIGNAL(clicked()),this,SLOT(connecttoServer()));
    connect(autosendBox,SIGNAL(stateChanged(int)),this,SLOT(autosend(int)));
    connect(sendDbMsgBox,SIGNAL(stateChanged(int)),this,SLOT(DbMsgsend(int)));
    connect(sendbtn,SIGNAL(clicked()),this,SLOT(connecttoServer()));
    connect(intervalEdit,SIGNAL(textChanged(const QString &)),this,SLOT(intervalValHandler(const QString&)));
    connect(cleanTextEditBtn,&QPushButton::clicked,this,[=](){sendareaEdit->clear();});
    connect(sendareaEdit,&QTextEdit::textChanged,this,[=](){
        if(sendareaEdit->toPlainText().isEmpty()){assemblebtn->setEnabled(false);parsebtn->setEnabled(false);}
        else{assemblebtn->setEnabled(true);parsebtn->setEnabled(true);}
    });
    // 解析发送栏中的报文数据
    connect(parsebtn,&QPushButton::clicked,this,[=](){
        QStringList slSendContent = sendareaEdit->toPlainText().split(" ");
        vetParseDat.clear();
        for(int i = 0; i < slSendContent.size(); i++)
        {
            vetParseDat.append(slSendContent[i]);
         }
        emit ParseFinished();
    });
    // 将Item中所有数据收集到textedit中
    connect(assemblebtn,&QPushButton::clicked,this,[=](){
        emit AssembleMessage();
    });

    // timer
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(timerHander()));
    curCount = 0;
}

TcpClient::~TcpClient()
{

}
/*
* @brief 创建界面
* @note
*/
void TcpClient::customUI()
{
    widget = new QWidget;
    //widget->setStyleSheet("background-color: #ffffff;border:1px solid rgb(118, 118, 118);");
    QVBoxLayout* mainLayout = new QVBoxLayout;

    QGridLayout* topLayout = new QGridLayout;
    QLabel* iplab = new QLabel("IP地址");
    iplab->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);

    IpEdit = new QLineEdit;
    IpEdit->setFixedWidth(100);

    connectbtn = new QPushButton("连接");
    connectbtn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    connectbtn->setFixedWidth(40);

    linkstatusLab = new QLabel("状态:未连接");
    linkstatusLab->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    linkstatusLab->setFixedWidth(400);

    QLabel* toplabel = new QLabel;
    toplabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    cleanTextEditBtn = new QPushButton("清空");
    cleanTextEditBtn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    cleanTextEditBtn->setFixedWidth(100);
    parsebtn = new QPushButton("解析报文");
    parsebtn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    parsebtn->setFixedWidth(100);
    parsebtn->setEnabled(false);
    assemblebtn = new QPushButton("装配报文");
    assemblebtn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    assemblebtn->setFixedWidth(100);
    assemblebtn->setEnabled(false);

    topLayout->addWidget(iplab,0,0);
    topLayout->addWidget(IpEdit,0,1);
    topLayout->addWidget(connectbtn,0,2);
    topLayout->addWidget(linkstatusLab,0,3);
    topLayout->addWidget(toplabel,0,4);
    topLayout->addWidget(cleanTextEditBtn,0,5);
    topLayout->addWidget(parsebtn,0,6);
    topLayout->addWidget(assemblebtn,0,7);
    mainLayout->addLayout(topLayout,5);

    sendareaEdit = new QTextEdit;
    //sendareaEdit->append("<img src=\"://Image//Icon//icon.png\" />");
    mainLayout->addWidget(sendareaEdit,20);

    QGridLayout* bottomLayout = new QGridLayout;
    autosendBox = new QCheckBox("自动发送");
    autosendBox->setEnabled(false);
    sendDbMsgBox = new QCheckBox("发送db报文");
    QLabel* intervalLab = new QLabel("间隔");
    intervalLab->setAlignment(Qt::AlignRight);
    intervalLab->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);

    intervalEdit = new QLineEdit;
    intervalEdit->setFixedWidth(100);

    sendbtn = new QPushButton("发送");
    sendbtn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    sendbtn->setFixedWidth(40);

    QLabel* msLab = new QLabel("ms");
    msLab->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);

    sendstatusLab = new QLabel("状态:未发送");
    sendstatusLab->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
    sendstatusLab->setFixedWidth(100);

    QLabel* bottomlabel = new QLabel;
    bottomlabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    bottomLayout->addWidget(autosendBox,0,0);
    bottomLayout->addWidget(sendDbMsgBox,0,1);
    bottomLayout->addWidget(intervalLab,0,2);
    bottomLayout->addWidget(intervalEdit,0,3);
    bottomLayout->addWidget(msLab,0,4);
    bottomLayout->addWidget(sendbtn,0,5);
    bottomLayout->addWidget(sendstatusLab,0,6);
    bottomLayout->addWidget(bottomlabel,0,7);
    mainLayout->addLayout(bottomLayout,5);

    widget->setLayout(mainLayout);
    setContentsMargins(0,0,0,0);
    setCentralWidget(widget);
}
/*
* @brief 链接TCP服务器
* @note 先判定IP格式是否正确，匹配后链接服务器
*/
void TcpClient::connecttoServer()
{
    // IP地址匹配
    QRegExp regExp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
    QString ip = IpEdit->text();
    if(regExp.exactMatch(ip))
    {
        tcpSocket.connectToHost(ip, 8080);
        bool connected = tcpSocket.waitForConnected();
        linkstatusLab->setText(QString("状态:连接%1").arg(connected?"成功":"失败"));
    }
    else
    {
        linkstatusLab->setText("状态:IP地址格式错误");
    }
}
/*
* @brief 发送文本到socket
* @note
*/
void TcpClient::sendRequest(const QString& request)
{
    tcpSocket.write(request.toStdString().c_str(), strlen(request.toStdString().c_str()));
    tcpSocket.waitForBytesWritten();
}
/*
* @brief 错误信息
* @note
*/
void TcpClient::error(QAbstractSocket::SocketError)
{
    linkstatusLab->setText(QString("状态:连接失败,错误原因:%1").arg(tcpSocket.errorString()));
    sendbtn->setEnabled(false);
}
/*
* @brief 成功返回
* @note
*/
void TcpClient::successed()
{
    linkstatusLab->setText(QString("状态:连接成功"));
    sendbtn->setEnabled(true);
}
/*
* @brief 持续发送
* @note
*/
void TcpClient::autosend(int state)
{
    if(Qt::Checked == state)
    {
        if(!intervalEdit->text().isEmpty()){}
        timer->start(intervalEdit->text().toInt());
    }
    else if(Qt::Unchecked == state)
    {
        timer->stop();
    }
    else
    {

    }
}
/*
* @brief 持续发送
* @note
*/
void TcpClient::timerHander()
{
    if(!timer->isActive())
    {
        timer->start(intervalEdit->text().toInt());
    }
    if(curCount < slMsgFrames.size() - 1)
    {
        curCount++;
    }
    else
    {
        curCount = 0;
    }
    if(Qt::Checked == autosendBox->checkState())
    {
        sendRequest(sendareaEdit->toPlainText());
    }
    else if(Qt::Checked == sendDbMsgBox->checkState())
    {
        sendRequest(slMsgFrames.at(curCount));
        sendareaEdit->clear();
        sendareaEdit->setText(slMsgFrames.at(curCount));
    }
}
/*
* @brief 停止发送
* @note
*/
void TcpClient::stopSend()
{
    tcpSocket.close();
}
/*
* @brief 关闭socket
* @note
*/
void TcpClient::connectionClosedByServer()
{
    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();
}
/*
* @brief 发送一次文本到服务器
* @note
*/
void TcpClient::sendonce()
{
    sendRequest(sendareaEdit->toPlainText());
}
/*
* @brief 设置checkbox
* @note
*/
void TcpClient::intervalValHandler(const QString& interval)
{
    if(interval.isEmpty())
    {
        autosendBox->setEnabled(false);
        sendstatusLab->setText("CheckBox不可用");
    }
    else
    {
        autosendBox->setEnabled(true);
        sendstatusLab->setText("CheckBox可用");
    }
}
/*
* @brief 获取配置文件解析后的数据
* @note
*/
QVector<QString>& TcpClient::getParseData()
{
    return vetParseDat;
}
/*
* @brief 文本框内设置文本
* @note
*/
void TcpClient::setSendAreaText(const QString& text)
{
    sendareaEdit->clear();
    sendareaEdit->setText(text);
}

void TcpClient::setMsgFrames(QStringList slmsgs)
{
    slMsgFrames = slmsgs;
}

void TcpClient::DbMsgsend(int state)
{
    if(Qt::Checked == state)
    {
        timer->start(intervalEdit->text().toInt());
    }
    else if(Qt::Unchecked == state)
    {
        timer->stop();
    }
    else
    {

    }
}
